var conObj = [];
var limit = 15;
var tid;
var orgId = -1;
var weightTypeObj = new Object(),materialObj = new Object(),storageObj = new Object();
var weightType = 1,carType = 2;
var isAdmin = $('.isAdmin').val(),isCheck = $('.isCheck').val(),isFinance = $('.isFinance').val();
var isInsert = $('.isInsert').val(),isDelete = $('.isDelete').val(),isUpdate = $('.isUpdate').val();
layui.use(['laypage', 'table', 'form', 'laydate'], function(){
    var table = layui.table;
    var form = layui.form,laydate = layui.laydate;
    weightTypeObj = convertEnumToObj(weightTypeList);
    storageObj = convertEnumToObj(storageList);
    // $.each(materialList, function (index, val) {
    //     materialObj[val.id] = val.nameNorms;
    // });
    if (isInsert == 0)
        $('.btn-add').hide();
    $(".startTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    laydate.render({
        elem: '#search-startTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#search-endTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#add-inTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#add-outTime',
        type: 'datetime'
    });
    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'code', title: '编号', width: 120, align: 'center'}
            ,{field: 'supplier', title: '供应商', width:160, align: 'center'}
            ,{field: 'material', title: '材料名称', width: 140, align: 'center',templet:function (val) {
                if (val.outTime == null)
                    return '<label style="color: #FF5722;">' + val.material + '</label>'
                return val.material;
            }}
            ,{field: 'carNo', title: '车牌号', width:120, align: 'center',templet:function (val) {
                if (val.outTime == null)
                    return '<label style="color: #FF5722;">' + val.carNo + '</label>'
                return val.carNo;
            }}
            ,{field: 'storage', title: '仓位', width:120, align: 'center'}
            ,{field: 'gross', title: '毛重(吨)', width:140, align: 'center', totalRow: true,templet:function (val) {
                var checked = $('.switchDisplay').prop("checked");
                var netWeight = parseFloat(val.netWeight / 1000);
                if (checked && netWeight > 35) {
                    var calcWeight = netWeight % 35;
                    var tare = parseFloat(val.tare / 1000);
                    var addWeight = parseFloat(calcWeight / 35);
                    var gross = parseFloat(addWeight + 35 + tare);
                    return gross.toFixed(2);
                } else {
                    if (val.gross != null)
                        return parseFloat(val.gross / 1000).toFixed(2);
                    return 0;
                }
            }}
            ,{field: 'netWeight', title: '净重(吨)', width:140, align: 'center', totalRow: true,templet:function (val) {
                if (val.netWeight != null) {
                    var checked = $('.switchDisplay').prop("checked");
                    var netWeight = parseFloat(val.netWeight / 1000);
                    if (checked && netWeight > 35) {
                        var calcWeight = netWeight % 35;
                        var addWeight = parseFloat(calcWeight / 35);
                        var weight = parseFloat(addWeight + 35);
                        return weight.toFixed(2);
                    } else {
                        if (val.supplierNetWeight > val.netWeight)
                            return '<label style="color: #1E9FFF;">' + netWeight + '</label>'
                        return netWeight;
                    }
                }
                return 0;
            }}
            ,{field: 'tare', title: '皮重(吨)', width:140, align: 'center', totalRow: true,templet:function (val) {
                if (val.tare != null)
                    return parseFloat(val.tare / 1000).toFixed(2);
                return 0;
            }}
            ,{field: 'supplierNetWeight', title: '供方净重(吨)', width:140, align: 'center', totalRow: true,templet:function (val) {
                if (val.supplierNetWeight != null) {
                    // var checked = $('.switchDisplay').prop("checked");
                    var supplierNetWeight = parseFloat(val.supplierNetWeight / 1000);
                    // if (checked || supplierNetWeight > 35) {
                    //     var calcWeight = supplierNetWeight % 35;
                    //     var addWeight = parseFloat(calcWeight / 35);
                    //     var weight = parseFloat(addWeight + 35);
                    //     return weight.toFixed(2);
                    // } else {
                        return supplierNetWeight.toFixed(2);
                    // }
                }
                return 0;
            }}
            ,{field: 'inTime', title: '入场时间', width:140, align: 'center'}
            ,{field: 'outTime', title: '出场时间', width:140, align: 'center'}
            ,{field: 'isPrint', title: '是否打印', width:100, align: 'center',templet:function(val){
                if (val.isPrint == 1)
                    return '已打印';
                else
                    return '未打印';
            }}
            ,{field: 'printTime', title: '打印时间', width:140, align: 'center'}
            ,{field: 'creator', title: '操作人', width:100, align: 'center'}
            ,{field: 'remark', title: '备注', width: 200, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 190, align:'center', templet:function (val) {
                var str = '';
                if (isAdmin == 1 || isDelete == 1) {
                    if (val.status == 0)
                        str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">作废</a>';
                    else
                        str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
                } else {
                    str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">详情</a>';
                }
                // if (isUpdate == 1)
                //     str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                if (val.isCheck == 0)
                    if (isAdmin == 1 || isCheck == 1)
                        str += '<a lay-event="examine" href="javascript:void(0)" class="layui-btn layui-btn-xs">审核</a>';
                str += '<a lay-event="print" href="javascript:void(0)" class="layui-btn layui-btn-xs">打印</a>';
                return str;
            }}
        ]
    ];
    table.render({
        elem: '#body-list'
        ,url: '/material-weight/page'
        ,method: 'post'
        ,page: true
        ,totalRow: true
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            weightType: weightType,
            carType:carType,
            searchType:$('.search-searchType').val()
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res)
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            if (isAdmin != 1) {
                layer.msg('您无操作权限');
                return ;
            }
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要删除？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option = {
                    id: id,
                    orgId:data.orgId,
                    status: updateStatus
                };
                save(option, "/material-weight/update-status");
                layer.closeAll();
            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            updateWindow(data);
        } else if (layEvent == 'print') {//打印

        } else if (layEvent == 'examine') {
            if (data.isCheck == 1) {
                layer.msg('该磅单已审核,请刷新查看');
                return;
            }
            layer.confirm('是否审核该磅单?', {
                btn: ['确定', '取消']
            }, function(index, layero){
                var option = {
                    ids: id,
                };
                save(option, "/main-material/check-weight");
                layer.closeAll();
            });
        }
    });
    table.on('rowDouble(body-list)', function(obj){
        tid = obj.data.id;
        updateWindow(obj.data);
    });
    form.on('switch(switchDisplay)', function(data){
        var checked = this.checked;
        layer.confirm('是否开启参数设置？',{
            btn: ['确定', '取消']
        }, function(index, layero){
            layer.closeAll();
        },function (index, layero) {
            console.log(checked)
            if (checked) {
                $('.switchDisplay').prop("checked", false);
            } else {
                $('.switchDisplay').prop("checked", true);
            }
            form.render();
        });
    });
    form.on('select(search-searchType)', function(data) {
        $(".btn-query").trigger("click");
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            $(".btn-query").trigger("click");
        }
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var supplierId = $('.search-supplier').val();
        var searchVal = $('.search-text').val();
        // var orgId = $('.search-origin').val();
        var materialId = $('.search-material').val();
        var startTime = $('.search-startTime').val();
        var endTime = $('.search-endTime').val();
        var searchType = $('.search-searchType').val();

        var option = {page:1,limit:limit,carType:carType,weightType:weightType};
        if (!isNull(materialId))
            option['materialId'] = materialId;
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(supplierId))
            option['supplierId'] = supplierId;
        if (!isNull(searchType))
            option['searchType'] = searchType;
        if (!isNull(startTime))
            option['startTime'] = startTime;
        if (!isNull(endTime))
            option['endTime'] = endTime;
        console.log(option)
        table.reload('body-list', {
            where: option,page:{curr:1}
        });
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-supplier)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-material)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(add-origin)', function(data) {//新增、修改级联刷新供应商
        if (!isNull(data.value)) {
            var orgId = data.value;
            loadSelectData({orgId:orgId}, '/mainsupplier/by-org', 0);
            var storeType = $('.add-material').find("option:selected").attr('data-type');
            if (storeType != null) {
                setTimeout(function () {
                    loadSelectData({orgId:orgId,type:storeType}, '/system/storage/find-org', 2);
                },300);
            }
            var supplierId = $('.add-supplier').val();
            if (supplierId != null) {
                setTimeout(function () {
                    loadSelectData({orgId:orgId,supplierId:supplierId}, '/main-material/find-supplier', 1);
                }, 200);
            }
        }
    });
    form.on('select(add-supplier)', function(data) {
        if (!isNull(data.value)) {
            var supplierId = data.value;
            var orgId = $('.add-origin').val();
            if (orgId != null)
                loadSelectData({orgId:orgId,supplierId:supplierId}, '/main-material/find-supplier', 1);
        }
    });
    form.on('select(add-material)', function(data) {
        if (!isNull(data.value)) {
            var orgId = $('.add-origin').val();
            var storeType = $('.add-material').find("option:selected").attr('data-type');
            if (storeType != null) {
                setTimeout(function () {
                    loadSelectData({orgId:orgId,type:storeType,materialId:data.value}, '/system/storage/find-org', 2);
                },300);
            }
        }
    });
    $('.btn-add').on('click', function () {
        $('.addModal').show();
        var orgId = $('.add-origin').val();
        loadSelectData({orgId:orgId}, '/mainsupplier/by-org', 0);
        // setTimeout(function () {
        //     loadSelectData({orgId:orgId,curr:1,limit:10000}, '/system/storage/page', 2);
        // },300);
    });
    $(".addModal .close").on("click", function() {
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
        tid = -1;
    });
    $('.add-gross').keyup(function () {//实时计算皮重
        validateMealStandard(this);
        var gross = convertNumber($('.add-gross').val());
        var netWeight = convertNumber($('.add-netWeight').val());
        if (gross < 0 || netWeight < 0)
            return ;
        var tare = gross - netWeight;
        $('.add-tare').val(tare);
    });
    $('.add-netWeight').keyup(function () {//实时计算皮重
        validateMealStandard(this);
        var gross = convertNumber($('.add-gross').val());
        var netWeight = convertNumber($('.add-netWeight').val());
        if (gross < 0 || netWeight < 0)
            return ;
        var tare = gross - netWeight;
        $('.add-tare').val(tare);
    });
    $('.add-supplierGross').keyup(function () {//实时计算皮重
        validateMealStandard(this);
        var gross = convertNumber($('.add-supplierGross').val());
        var netWeight = convertNumber($('.add-supplierNetWeight').val());
        if (gross < 0 || netWeight < 0)
            return ;
        var tare = gross - netWeight;
        $('.add-supplierTare').val(tare);
    });
    $('.add-supplierNetWeight').keyup(function () {//实时计算皮重
        validateMealStandard(this);
        var gross = convertNumber($('.add-supplierGross').val());
        var netWeight = convertNumber($('.add-supplierNetWeight').val());
        if (gross < 0 || netWeight < 0)
            return ;
        var tare = gross - netWeight;
        $('.add-supplierTare').val(tare);
    });

    //点击添加提交
    form.on('submit(addBtns)', function() {
        var isAdmin = $('.isAdmin').val();
        if (isAdmin == 0) {
            layer.msg('您没有操作权限~！');
            return;
        }
        var orgName = $.trim($(".addModal .add-origin").find("option:selected").text());//公司
        var orgId = $.trim($(".addModal .add-origin").val());//公司
        var supplier = $.trim($(".addModal .add-supplier").find("option:selected").text());//
        var supplierId = $.trim($(".addModal .add-supplier").val());//
        var material = $.trim($(".addModal .add-material").find("option:selected").text());//
        var materialId = $.trim($(".addModal .add-material").val());//
        var remark = $.trim($(".addModal .remark").val());//备注
        var storageId = $.trim($(".addModal .add-storage").val());//仓位ID
        var carNo = $.trim($(".addModal .add-carNo").val());//车牌
        var gross = $.trim($(".addModal .add-gross").val());//毛重
        var netWeight = $.trim($(".addModal .add-netWeight").val());//净重
        var tare = $.trim($(".addModal .add-tare").val());//皮重
        var supplierGross = $.trim($(".addModal .add-supplierGross").val());//供应商毛重
        var supplierNetWeight = $.trim($(".addModal .add-supplierNetWeight").val());//供应商净重
        var supplierTare = $.trim($(".addModal .add-supplierTare").val());//供应商皮重
        var inTime = $.trim($(".addModal .add-inTime").val());//入场
        var outTime = $.trim($(".addModal .add-outTime").val());//出场
        var phone = $.trim($(".addModal .add-phone").val());//电话
        var driver = $.trim($(".addModal .add-driver").val());//电话
        var isCheck = $.trim($(".addModal .add-isCheck").val());//是否审核
        var isBill = $.trim($(".addModal .add-isBill").val());//是否结算
        var remark = $.trim($(".addModal .remark").val());//备注
        if (isNull(orgId)) {
            layer.msg("请选择所属公司！");
            return ;
        }
        if (isNull(storageId) || isNull(storageId)) {
            layer.msg("请选择材料仓位信息！");
            return ;
        }
        if (isNull(supplier) || isNull(supplierId)) {
            layer.msg("请选择供应商！");
            return ;
        }
        if (isNull(materialId) || isNull(material)) {
            layer.msg("请选择材料！");
            return ;
        }
        if (isNull(carNo)) {
            layer.msg("请输入车牌号！");
            return ;
        }
        if (isNull(gross)) {
            layer.msg("请输入毛重！");
            return ;
        }
        if (isNull(netWeight)) {
            layer.msg("请输入净重！");
            return ;
        }
        if (isNull(tare)) {
            layer.msg("请输入皮重！");
            return ;
        }
        if (gross > 200) {
            layer.msg("最大毛重不能超过200吨！");
            return ;
        }
        if (netWeight > 200) {
            layer.msg("最大净重不能超过200吨！");
            return ;
        }
        if (tare > 200) {
            layer.msg("最大皮重不能超过200吨！");
            return ;
        }
        if (isNull(inTime)) {
            layer.msg("请选择入场时间！");
            return ;
        }
        if (isNull(outTime)) {
            layer.msg("请选择出场时间！");
            return ;
        }
        gross = parseFloat(gross * 1000).toFixed(2);
        netWeight = parseFloat(netWeight * 1000).toFixed(2);
        tare = parseFloat(tare * 1000).toFixed(2);
        if (supplierGross != null && supplierNetWeight > 0)
            supplierGross = parseFloat(supplierGross * 1000).toFixed(2);
        if (supplierTare != null && supplierTare > 0)
            supplierTare = parseFloat(supplierTare * 1000).toFixed(2);
        supplierNetWeight = parseFloat(supplierNetWeight * 1000).toFixed(2);
        var options = {driver:driver,orgId:orgId,remark:remark,supplierNetWeight:supplierNetWeight,
            gross:gross,netWeight:netWeight,tare:tare,storageId:storageId,material:material,
            phone:phone,isBill:isBill,carType:2,isCheck:isCheck,carNo:carNo,supplierId:supplierId,
            materialId:materialId,supplier:supplier,supplierGross:supplierGross,
            supplierTare:supplierTare
        };
        if (!isNull(inTime))
            options['inTime'] = inTime;
        if (!isNull(outTime))
            options['outTime'] = outTime;
        if (!isNull(tid) && tid != -1) {
            options['id'] = tid;
            save(JSON.stringify(options), "/material-weight/update", 1,'application/json');
        } else {
            save(JSON.stringify(options), "/material-weight/save", 0, 'application/json');
        }
    });
    function validateMealStandard(e){//金额保留两位小数
        var val = $(e).val();
        var t = val.charAt(0);
        var standard = val.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '');
        if (standard >= 999999999.99){
            if (t == '-')
                $(e).val('-' + 999999999.99);
            else
                $(e).val(999999999.99);
        }else {
            if (t == '-')
                $(e).val('-' + standard);
            else
                $(e).val(standard);
        }
    }
    function save(option, url,type,contentType) {//新增或修改
        console.log(option)
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data:option,
            timeout: 30000,
            contentType: contentType,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    if (res.msg != null)
                        layer.msg(res.msg);
                    else
                        layer.msg("更新成功!");
                    $(".btn-query").trigger("click");
                    $(".addModal").hide();
                    $(".addModal input").val("");
                    $(".addModal select").val("");
                    $(".addModal textarea").val("");
                    if (type == 1)
                        tid = -1;
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    function loadSelectData(obj, url, type) {//加载供应商信息
        var loading = layer.load(1);
        $.ajax({
            url:url,
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data:obj,
            success: function(res) {
                layer.close(loading);
                console.log(res)
                if(res.code == 0 && res.data != null) {
                    var data = res.data;
                    var html = '';
                    if (type == 2)
                        html = '<option value="">请选择仓位</option>';
                    if (type == 1)
                        html = '<option value="">请选择材料</option>';
                    if (type == 0)
                        html = '<option value="">请选择供应商</option>';
                    if (type == 0) {
                        $.each(data, function(i, v) {
                            html += '<option value="' + v.id + '">' + v.fullName + '</option>';
                        });
                        $('.add-supplier').html(html);
                        if (obj.supplierId != null)
                            $('.add-supplier').val(obj.supplierId);
                        form.render();
                    } else if (type == 1) {
                        $.each(data, function(i, v) {
                            html += '<option data-type="' + v.storeType + '" value="' + v.materialId + '">' + v.nameNorms + '</option>';
                        });
                        $('.add-material').html(html);
                        if (obj.materialId != null) {

                            $('.add-material').val(obj.materialId);
                        }
                        form.render();
                    } else if (type == 2) {
                        $.each(data, function(i, v) {
                            html += '<option value="' + v.id + '">' + v.name + '</option>';
                        });
                        $('.add-storage').html(html);
                        form.render();
                        if (obj.storageId != null) {
                            console.log(obj)
                            $('.add-storage').val(obj.storageId);
                        }
                    }
                } else {
                    if (type == 2)
                        $('.add-storage').html('<option value="">暂无数据</option>');
                    if (type == 1)
                        $('.add-material').html('<option value="">暂无数据</option>');
                    if (type == 0)
                        $('.add-supplier').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function(res) {
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        });
    }

    function updateWindow(data) {
        $('.addModal').show();
        if (data.id != null)
            tid = data.id;
        $('.addModal .add-code').val(data.code);
        $('.addModal .add-origin').val(data.orgId);
        // $('.addModal .update-material').val(data.mid);
        if (data.supplierId != null)
            $('.addModal .add-supplier').val(data.supplierId);
        if (data.materialId != null)
            $('.addModal .add-material').val(data.materialId);
        if (data.storageId != null)
            $('.addModal .add-storage').val(data.storageId);
        if (data.carNo != null)
            $('.addModal .add-carNo').val(data.carNo);
        if (data.gross != null) {
            var gross = data.gross / 1000;
            $('.addModal .add-gross').val(gross.toFixed(2));
        }
        if (data.netWeight != null) {
            var netWeight = data.netWeight / 1000;
            $('.addModal .add-netWeight').val(netWeight.toFixed(2));
        }
        if (data.tare != null) {
            var tare = data.tare / 1000;
            $('.addModal .add-tare').val(tare.toFixed(2));
        }
        if (data.supplierGross != null) {
            var gross = data.supplierGross / 1000;
            $('.addModal .add-supplierGross').val(gross.toFixed(2));
        }
        if (data.supplierNetWeight != null) {
            var netWeight = data.supplierNetWeight / 1000;
            $('.addModal .add-supplierNetWeight').val(netWeight.toFixed(2));
        }
        if (data.supplierTare != null) {
            var tare = data.supplierTare / 1000;
            $('.addModal .add-supplierTare').val(tare.toFixed(2));
        }
        if (data.inTime != null)
            $('.addModal .add-inTime').val(data.inTime);
        if (data.outTime != null)
            $('.addModal .add-outTime').val(data.outTime);
        if (data.driver != null)
            $('.addModal .add-driver').val(data.driver);
        if (data.isCheck != null)
            $('.addModal .add-isCheck').val(data.isCheck);
        if (data.isBill != null)
            $('.addModal .add-isBill').val(data.isBill);
        if (data.phone != null)
            $('.addModal .add-phone').val(data.phone);
        $('.addModal .remark').val(data.remark);
        loadSelectData({orgId:data.orgId,supplierId:data.supplierId}, '/mainsupplier/by-org', 0);
        setTimeout(function () {
            loadSelectData({orgId:data.orgId,materialId:data.materialId,storageId:data.storageId}, '/system/storage/find-org', 2);
        },100);
        setTimeout(function () {
            loadSelectData({orgId:data.orgId, supplierId:data.supplierId,materialId:data.materialId}, '/main-material/find-supplier', 1);
        }, 200);
        form.render();
    }
});